package com.storage.web.access;

import com.storage.common.utils.StringUtils;
import com.storage.framework.jwt.Constant;
import com.storage.framework.util.JwtUtil;
import com.storage.framework.web.OperationContext;
import com.storage.framework.web.OperationContextHolder;
import com.storage.system.domain.StorageUser;
import com.storage.system.service.IStorageUserService;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登陆、权限校验拦截器
 *
 * @author hzhang7
 */
@Component
public class PermissionHandlerInterceptor implements HandlerInterceptor {

    public static PermissionHandlerInterceptor permissionHandlerInterceptor;

    @Autowired
    private IStorageUserService storageUserService;

    @PostConstruct
    public void init(){
        permissionHandlerInterceptor = this;
        permissionHandlerInterceptor.storageUserService = this.storageUserService;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        OperationContext context = resetOperationContext(request, response);
        if(context == null) {
            throw new IncorrectCredentialsException("token无效或已过期");
        }

        return true;
    }

    private OperationContext resetOperationContext(HttpServletRequest request, HttpServletResponse response) {
        OperationContextHolder.clear();
        OperationContext context = getOperationContext(request, response);
        OperationContextHolder.set(context);
        return context;
    }

    private OperationContext getOperationContext(HttpServletRequest request, HttpServletResponse response) {
        // 解析token获取电话，查询用户对象，构造 context
        // 解密获得token
        String token = request.getHeader(Constant.TOKEN_HEADER_NAME);
        if (StringUtils.isBlank(token)) {
            return null;
        }
        String phone = JwtUtil.getPhone(token);
        StorageUser user = permissionHandlerInterceptor.storageUserService.selectUserByPhoneNumber(phone);
        if(user != null) {
            OperationContext context = new OperationContext();
            context.setStorageUser(user);
            return context;
        }
        return null;
    }
}
